package com.example.interceptors;

import com.example.util.JwtUtil;
import com.example.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor  implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //令牌认证
        String token = request.getHeader("Authorization");
        //验证token是否合法
        try{
            //从redis中获取相同的token
            ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
            String redisToken = ops.get(token);
            if (redisToken == null){
                //token已经失效，redis中没有token
                throw new RuntimeException("token已经失效");
            }

            Map<String,Object> claims = JwtUtil.parseToken(token);
            //把业务数据放到ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true;
        }catch (Exception e){
            //http响应状态码为401
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求处理完成后，移除ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
